package com.guohao.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guohao.reggie.common.R;
import com.guohao.reggie.entity.User;
import com.guohao.reggie.service.UserService;
import com.guohao.reggie.utils.SMSUtils;
import com.guohao.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 移动端登录管理
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送手机验证码短信
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {

        // 1. 获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            // 2. 生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code :{}", code);
            // 3. 调用阿里云提供的短信API完成发送短信
//            SMSUtils.sendMessage("签名","手机号",phone,code);

            // 4. 需要将生成的验证码存到Session中
            session.setAttribute(phone, code);

            return R.success("手机验证码发送成功!");
        }

        return R.success("手机验证码发送失败!");
    }

    /**
     * 移动端登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        System.out.println("map = " + map.toString());

        //1 获取手机号
        String phone = map.get("phone").toString();

        //2 获取验证码

        String code = map.get("code").toString();
        //3 从Session中获取保存的验证码
        Object sessionCode = session.getAttribute(phone);

        //4 进行验证码的比对(页面提交的验证码和Session中的code对比)
        if (sessionCode != null && sessionCode.equals(code)){
            //5 对比成功 登录成功

            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);

            User user = userService.getOne(wrapper);
            if (user == null){
                //6 新用户 自动注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("登录失败");
    }

}
